import { Track } from '@/store/tracksTypes';
import { BaseClipItem } from '@/components/TimelineContentRow';
import { ITrack } from '@/store/types/track';

/**
 * 检查单个轨道中的素材片段是否有重叠
 * @param track 轨道对象
 * @returns 重叠信息数组，如果没有重叠则返回空数组
 */
export const checkTrackOverlaps = (track: Track): Array<{ clip1: BaseClipItem; clip2: BaseClipItem }> => {
    const overlaps: Array<{ clip1: BaseClipItem; clip2: BaseClipItem }> = [];

    // 如果轨道可以堆叠素材，或者是视频轨道，则不需要检查重叠
    if (track.canStackItems || track.type === 'video') {
        return overlaps;
    }

    const items = track.items;

    // 遍历所有素材片段，检查每对片段是否重叠
    for (let i = 0; i < items.length; i++) {
        for (let j = i + 1; j < items.length; j++) {
            const item1 = items[i];
            const item2 = items[j];

            // 检查两个片段是否重叠
            // 片段1的结束时间 = 开始时间 + 持续时间
            const item1End = item1.start + item1.duration;
            const item2End = item2.start + item2.duration;

            // 如果片段1的开始时间在片段2的时间范围内，或者片段2的开始时间在片段1的时间范围内，则认为有重叠
            const isOverlapping = (item1.start >= item2.start && item1.start < item2End) || (item2.start >= item1.start && item2.start < item1End);

            if (isOverlapping) {
                overlaps.push({ clip1: item1, clip2: item2 });
            }
        }
    }

    return overlaps;
};

/**
 * 检查所有轨道中的素材片段是否有重叠
 * @param tracks 轨道数组
 * @returns 包含重叠信息的轨道数组，如果没有重叠则返回空数组
 */
export const checkAllTracksOverlaps = (tracks: Track[]): Array<{ track: Track; overlaps: Array<{ clip1: BaseClipItem; clip2: BaseClipItem }> }> => {
    return tracks.map((track) => ({
        track,
        overlaps: checkTrackOverlaps(track),
    }));
};

/**
 * 获取轨道上最后一个片段的结束时间
 * @param track 轨道对象
 * @returns 最后一个片段的结束时间（微秒），如果没有片段则返回0
 */
export const getTrackLastSegmentEndTime = (track: ITrack): number => {
    if (!track.segments || track.segments.length === 0) {
        return 0;
    }
    
    let maxEndTime = 0;
    for (const segment of track.segments) {
        const endTime = segment.target_timerange.start + segment.target_timerange.duration;
        maxEndTime = Math.max(maxEndTime, endTime);
    }
    
    return maxEndTime;
};

/**
 * 获取轨道上所有片段的结束时间
 * @param track 轨道对象
 * @returns 所有片段结束时间的数组（微秒）
 */
export const getTrackSegmentEndTimes = (track: ITrack): number[] => {
    if (!track.segments || track.segments.length === 0) {
        return [];
    }
    
    return track.segments.map(segment => 
        segment.target_timerange.start + segment.target_timerange.duration
    );
};

/**
 * 生成重叠提示信息
 * @param tracksWithOverlaps 包含重叠信息的轨道数组
 * @returns 提示信息字符串
 */
export const generateOverlapMessage = (
    tracksWithOverlaps: Array<{
        track: Track;
        overlaps: Array<{ clip1: BaseClipItem; clip2: BaseClipItem }>;
    }>
): string => {
    if (tracksWithOverlaps.length === 0) {
        return '';
    }

    let message = '发现以下轨道中存在素材重叠，请先调整：\n';

    tracksWithOverlaps.forEach(({ track, overlaps }) => {
        message += `- ${track.title || '未命名轨道'}（轨道类型：${track.type}）\n`;
        overlaps.forEach(({ clip1, clip2 }) => {
            message += `  - 素材 ${clip1.id} 和素材 ${clip2.id} 发生重叠\n`;
        });
    });

    return message;
};

/**
 * 生成轨道的层级render_index
 * @param trackArrayLength 轨道数组长度
 * @returns 层级render_index
 */
export const generateRenderIndex = (trackArrayLength: number): number => {
    return trackArrayLength * 100;
};
